package com.github.thinwonton.springboot.showcase.multidatasource.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE + 100)
@Component
public class DynamicDataSourceAspect {

    @Around("@annotation(DS)")
    public Object aroundAccount(ProceedingJoinPoint pjp) throws Throwable {
        try {

            //获得当前访问的class
            Class<?> className = pjp.getTarget().getClass();
            //获得访问的方法名
            String methodName = pjp.getSignature().getName();
            //得到方法的参数的类型
            Class[] argClass = ((MethodSignature) pjp.getSignature()).getParameterTypes();

            // 得到访问的方法对象
            Method method = className.getMethod(methodName, argClass);
            // 判断是否存在@DS注解
            DatabaseType databaseType = DatabaseType.ACCOUNT;
            if (method.isAnnotationPresent(DS.class)) {
                DS annotation = method.getAnnotation(DS.class);
                // 取出注解中的数据源名
                databaseType = annotation.value();
            }

            DatabaseContextHolder.setDatabaseType(databaseType);
            return pjp.proceed();
        } finally {
            DatabaseContextHolder.clearDB();
        }
    }
}